package com.qf.hospital.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.qf.hospital.dto.SysRoleDTO;
import com.qf.hospital.entity.SysMenu;
import com.qf.hospital.entity.SysRole;
import com.qf.hospital.entity.SysRoleExample;
import com.qf.hospital.enums.HospitalExceptionEnums;
import com.qf.hospital.exception.HospitalException;
import com.qf.hospital.mapper.SysRoleMapper;
import com.qf.hospital.service.SysMenuService;
import com.qf.hospital.service.SysRoleService;
import com.qf.hospital.utils.ExampleUtil;
import com.qf.hospital.vo.LayUIDTreeVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * @author ASUS
 * @version V1.0
 * @Project hospital
 * @Package com.qf.hospital.service.impl
 * @Date 2021/10/18 16:07
 */
@Service
public class SysRoleServiceImpl implements SysRoleService {

    Logger log = LoggerFactory.getLogger(SysRoleServiceImpl.class);

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMapper sysRoleMapper;

    /**
     * 查询所有权限
     * @return
     */
    @Override
    public List<SysRole> findAll() {
        return sysRoleMapper.selectByExample(null);
    }

    /**
     * 根据条件查询权限
     * @param sysRoleDTO
     * @param page
     * @param limit
     * @return
     */
    @Override
    public PageInfo<SysRole> loadAllRole(SysRoleDTO sysRoleDTO, Integer page, Integer limit) {
        PageHelper.startPage(page,limit);
        SysRoleExample sysRoleExample = new SysRoleExample();
        SysRoleExample.Criteria criteria = sysRoleExample.createCriteria();
        if(!StringUtils.isEmpty(sysRoleDTO.getRoleName())){
            criteria.andRoleNameLike(ExampleUtil.any(sysRoleDTO.getRoleName()));
        }
        if(!StringUtils.isEmpty(sysRoleDTO.getRoleDesc())){
            criteria.andRoleDescLike(ExampleUtil.any(sysRoleDTO.getRoleDesc()));
        }
        if(sysRoleDTO.getAvailable() != null){
            criteria.andAvailableEqualTo(sysRoleDTO.getAvailable());
        }
        List<SysRole> sysRoleList = sysRoleMapper.selectByExample(sysRoleExample);
        PageInfo<SysRole> pageInfo = new PageInfo<>(sysRoleList);
        return pageInfo;
    }

    /**
     * 编辑权限
     * @param sysRoleDTO
     */
    @Override
    public void updateRole(SysRoleDTO sysRoleDTO) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDTO,sysRole);
        int count = sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        if(count != 1){
            log.error("【修改权限信息】 修改失败！sysRole={}",sysRole);
            throw new HospitalException(HospitalExceptionEnums.ROLE_UPDATE_ERROR);
        }
    }

    /**
     * 删除权限
     * @param roleid
     */
    @Override
    public void deleteRole(Integer roleid) {
        SysRole sysRole = new SysRole();
        sysRole.setRoleId(roleid);
        sysRole.setAvailable(0);
        int count = sysRoleMapper.updateByPrimaryKeySelective(sysRole);
        if(count != 1){
            log.error("【删除权限信息】 删除失败！sysRole={}",sysRole);
            throw new HospitalException(HospitalExceptionEnums.ROLE_DELETE_ERROR);
        }
    }

    /**
     * 添加权限
     * @param sysRoleDTO
     */
    @Override
    public void insertRole(SysRoleDTO sysRoleDTO) {
        SysRole sysRole = new SysRole();
        BeanUtils.copyProperties(sysRoleDTO,sysRole);
        int count = sysRoleMapper.insert(sysRole);
        if(count != 1){
            log.error("【添加权限信息】 添加失败！sysRole={}",sysRole);
            throw new HospitalException(HospitalExceptionEnums.ROLE_INSERT_ERROR);
        }
    }

    /**
     * 展示全部菜单信息&回显角色拥有的信息
     * @param roleid
     * @return
     */
    @Override
    public List<LayUIDTreeVO> initRoleMenuTreeJson(Integer roleid) {
        List<SysMenu> sysMenuList = sysMenuService.findAll();

        List<Integer> roleMenuIds = sysRoleMapper.findMenuIdByRoleId(roleid);

        ArrayList<LayUIDTreeVO> layUIDTreeVOS = new ArrayList<>();
        for (SysMenu sysMenu : sysMenuList) {
            LayUIDTreeVO layUIDTreeVO = new LayUIDTreeVO();
            BeanUtils.copyProperties(sysMenu, layUIDTreeVO);
//            if(roleMenuIds.contains(roleMenuVO.getId())){
//                roleMenuVO.setCheckArr("1");
//            }else {
//                roleMenuVO.setCheckArr("0");
//            }
            layUIDTreeVO.setCheckArr(roleMenuIds.contains(layUIDTreeVO.getId()) ? "1":"0");
            layUIDTreeVOS.add(layUIDTreeVO);
        }
        return layUIDTreeVOS;
    }

    /**
     * 分配菜单
     * @param roleid
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = RuntimeException.class)
    public void saveRoleMenu(Integer roleid, Integer[] ids) {
        //1、先删除当前用户所拥有的菜单
        sysRoleMapper.deleteRoleMenus(roleid);
        //2、如果ids不为null并且长度大于0，批量添加角色的菜单信息
        if(ids != null && ids.length > 0){
            int count = sysRoleMapper.saveRoleMenu(roleid,ids);
            if(count != ids.length){
                log.error("【分配菜单信息】 分配菜单失败！roleid={},ids={}",roleid, Arrays.toString(ids));
                throw new HospitalException(HospitalExceptionEnums.ROLE_SAVE_ROLE_MENU_ERROR);
            }
        }
    }
}
